class articleModel{
  constructor(){
    this.db = require('../../config/db')
  }

  //获取所有文章信息
  article(){
    let sql = 'select * from article'
    return this.db.query(sql)
  }
  //搜索文章
  searchArticle(query,pagenum,pagesize){
    let sql = 'select * from article'
    if(query != ""){
      sql = sql + " where title like '%"+ query+"%' or content like '%"+ query+"%'"
    }else{
      sql = sql + " WHERE `title` IS NULL OR `content` IS NULL"
      
    }
    sql +=" limit ?,?"
    console.log(sql)
    return this.db.query(sql,[pagenum,pagesize])
  }
  //查询文章
  queryArticle(status,class_id,begin_pubdate,end_pubdate,pagenum,per_page,response_type){
    let sql = 'select * from article '
    let arr = [
      {
        name:'status',
        query:status
      },
      {
        name:'class_id',
        query:class_id
      },
      {
        name:'begin_pubdate',
        query:begin_pubdate
      },
      {
        name:'response_type',
        query:response_type
      },

    ]
    //过滤循环
    let params = arr.filter((item) => {
      console.log(`${item.name} ` + item.query)
      return (item.query != undefined || item.query != null);
    })
    if(params != 0){
      sql = sql + " where"
    }
    let param = []
    params.forEach((item) => {
      // console.log(item)
      // console.log(item.name)
      sql = sql + ` ${item.name} = ? and`
      param.push(item.query)
    })
    if(sql.length > 23){
      sql = sql.slice(0,(sql.length-3))
    }
    //时间排序
    sql = sql + " order by pubdate"
    // console.log(page)

    if(pagenum != null || pagenum != undefined){
      param.push(pagenum,per_page)
      sql = sql + " DESC limit ?,?"
    }
    return this.db.query(sql,param)
    
  }

  //发布文章
  publishArticle(title,author,status,content,images,class_id){
    let sql = "insert into article(title,author,status,content,images,class_id) values(?,?,?,?,?,?)"
    return this.db.query(sql,[title,author,status,content,images,class_id])
  }

  //修改文章状态
  updateStatus(status,id){
    let sql = 'update article set status = ? where id = ?'
    console.log(sql)
    return this.db.query(sql,[status,id])
  }

  //查询用户文章
  queryUserArticle(author){
    let sql = "select * from article where author = ? order by pubdate DESC"
    return this.db.query(sql,author)
  }

  //查询id文章
  queryArticleID(id){
    let sql = 'select * from article where id = ?'
    return this.db.query(sql,id)
  }

  //删除文章
  deleteArticleID(id){
    let sql = 'delete from article where id = ?'
    return this.db.query(sql,[id])
  }

  //修改文章信息
  updateArticle(title,author,content,images,class_id,id){
    let sql = "update article set title = ?,author = ?,content = ?,images = ?,class_id = ? where id = ?"
    return this.db.query(sql,[title,author,content,images,class_id,id])
  }

  //统计作者文章发布数
  countArticle(){
    let sql = "select author,count(*) as value from article group by author having value>0"
    return this.db.query(sql)
  }

}

module.exports = new articleModel()